import axios from 'axios'
import Api from '@/common/js/Api.js'
import MyUtil from '@/common/js/MyUtil.js'
import Mock from '@/common/js/MockData.js'

var mainVue;

function myGet(url, data, code200,loadtext) {
  mainVue.isLoading = MyUtil.load.countRequest();
  if(loadtext){
    mainVue.loadtext=loadtext
  }else{
    mainVue.loadtext='正在加载'
  }

  if(mainVue.loadtext===''){
    mainVue.showText = false
  }else{
    mainVue.showText = true
  }

  // console.log(url)

  function then(response) {
    mainVue.isLoading = MyUtil.load.countResponse()

    if (response.data.code === 200) {
      code200(response)
    } else {

      if (response.data.message) {
        mainVue.$message.error(response.data.message);
      } else {
        mainVue.$message.error("接口出错");
      }
    }
  }

  function error(err) {
    mainVue.isLoading = MyUtil.load.countResponse()
    mainVue.$message.error("请求异常：" + " " + err.message)
  }

  axios.get(url, data).then(then).catch(error)
}


function myGetWithoutLoad(url, data, code200, everyTodo) {

  function then(response) {
    everyTodo()
    if (response.data.code === 200) {
      code200(response)
    } else {
      if (response.data.message) {
        mainVue.$message.error(response.data.message);
      } else {
        mainVue.$message.error("接口出错");
      }
    }
  }

  function error(err) {
    everyTodo()

    mainVue.$message.error("请求异常：" + " " + err.message)
  }

  axios.get(url, data).then(then).catch(error)
}


export default {

  init: function (context) {
    mainVue = context
  },

  requestLogin: function (context) {
    var data = {
      params: {
        username: context.username,
        password: context.password,
      }
    };

    myGet(Api.loginUrl, data, function (response) {
      loginSuccess(response, context.remember)
    })

  },


  requestMenuList: function (context) {


    var data = {};
    myGet(Api.menuListUrl, data, function (response) {
      context.menuList = addMenuListRoute(response.data.data)

      //第一次请求成功后才执行，每次请求成功后才会继续请求，如果请求失败则停止自动请求
      // 等待5s后继续请求
      context.autoRequest()

    })

  },

  requestMenuListAuto: function (context) {


    var data = {};
    myGetWithoutLoad(Api.menuListUrl, data, function (response) {
      context.menuList = addMenuListRoute(response.data.data)

      //第一次请求成功后才执行，每次请求成功后才会继续请求，如果请求失败则停止自动请求
      // 等待5s后继续请求
      context.autoRequest()

    },function () {

    })

  },


  requestProgramList: function (context, lineName, pageNum, pageSize) {
    // var response = Mock.programData
    // Api.DefaultPageSize

    var data = {
      params: {
        lineName: lineName,
        page: pageNum,
        size: pageSize,
      }
    };


    myGet(Api.programListUrl, data, function (response) {
      var data = response.data.data
      context.tableHeader = MyUtil.tableData.makeProgramHeader(data.header)
      context.tableData = MyUtil.tableData.makeProgramList(data.list)
      context.page = MyUtil.tableData.makePage(data.pageNum, data.pageSize, data.total)

      //等待5s后继续请求
      if(MyUtil.programAutoCount ===0){
        context.autoRequest()
        MyUtil.programAutoCount++
        console.log('programAutoCount:'+MyUtil.programAutoCount)
      }


    })

  },

  requestProgramListAuto: function (context, lineName, pageNum, pageSize) {
    // var response = Mock.programData
    // Api.DefaultPageSize

    var data = {
      params: {
        lineName: lineName,
        page: pageNum,
        size: pageSize,
      }
    };


    myGetWithoutLoad(Api.programListUrl, data, function (response) {
      var data = response.data.data
      context.tableHeader = MyUtil.tableData.makeProgramHeader(data.header)
      context.tableData = MyUtil.tableData.makeProgramList(data.list)
      context.page = MyUtil.tableData.makePage(data.pageNum, data.pageSize, data.total)

      //等待5s后继续请求
      context.autoRequest()

    },function () {

    })

  },

  requestProgramFileList: function (context, lineName, pageNum, pageSize) {

    // Api.DefaultPageSize
    var data = {
      params: {
        lineName: lineName,
        page: pageNum,
        size: pageSize,
      }
    };

    //接口跟那个扫描记录是一样的
    myGet(Api.programListUrl, data, function (response) {
      var data = response.data.data
      context.tableHeader = MyUtil.tableData.makeProgramFileHeader(data.header)
      context.tableData = MyUtil.tableData.makeProgramFileList(data.list)
      context.page = MyUtil.tableData.makePage(data.pageNum, data.pageSize, data.total)
    })

  },

  //扫描记录
  requestScanList: function (context, lineName, programName, pageNum, pageSize, equipmentName, standPosition, startTime, endTime) {

    if (startTime !== '') {
      startTime = new Date(startTime).getTime()
    }
    if (endTime !== '') {
      endTime = new Date(endTime).getTime()
    }


    var data = {

      params: {
        lineName: lineName,
        programName: programName,
        equipmentName: equipmentName,
        username: "",
        standPosition: standPosition,
        startTime: startTime,
        endTime: endTime,
        page: pageNum,
        size: pageSize,
      }
    };

    // console.log('pageNum = '+pageNum)
    // console.log('data.page = '+data.params.page)
    myGet(Api.scanListUrl, data, function (response) {
      var data = response.data.data

      var tableData = MyUtil.tableData.makeScanList(data.list)
      var tableHeader = MyUtil.tableData.makeScanHeader(data.header)
      tableHeader = MyUtil.tableData.setTableHeaderAutoWidth(tableHeader, tableData)
      context.tableHeader = tableHeader
      context.tableData = tableData
      context.page = MyUtil.tableData.makePage(data.pageNum, data.pageSize, data.total)


      //等待5s后继续请求
      context.autoRequest()
    })

  },


  //扫描记录
  requestScanListAuto: function (context, lineName, programName, pageNum, pageSize, equipmentName, standPosition, startTime, endTime) {

    if (startTime !== '') {
      startTime = new Date(startTime).getTime()
    }
    if (endTime !== '') {
      endTime = new Date(endTime).getTime()
    }


    var data = {

      params: {
        lineName: lineName,
        programName: programName,
        equipmentName: equipmentName,
        username: "",
        standPosition: standPosition,
        startTime: startTime,
        endTime: endTime,
        page: pageNum,
        size: pageSize,
      }
    };

    // console.log('pageNum = '+pageNum)
    // console.log('data.page = '+data.params.page)
    myGet(Api.scanListUrl, data, function (response) {

      if(!MyUtil.isCheckedActionNow()){//有数据勾选中就不要刷新数据了

        var data = response.data.data
        var tableData = MyUtil.tableData.makeScanList(data.list)
        var tableHeader = MyUtil.tableData.makeScanHeader(data.header)
        tableHeader = MyUtil.tableData.setTableHeaderAutoWidth(tableHeader, tableData)
        context.tableHeader = tableHeader
        context.tableData = tableData
        context.page = MyUtil.tableData.makePage(data.pageNum, data.pageSize, data.total)

        // console.log('设置数据')
      }//不是完美的解决方法，不过还行



      //等待5s后继续请求  数据刷新中 这里传入空字符主要是实际上返回数据很快，不建议显示这个加载动画
      context.autoRequest()
    },'')

  },


  requestScanFilter: function (context, lineName) {

    // console.log('111requestScanFilter'+lineName)
    var data = {
      params: {
        lineName: lineName,
      }
    };
    myGet(Api.scanFilterUrl, data, function (response) {

      var data = response.data.data
      // console.log(data)
      context.deviceList = data.equis
      context.standList = data.posi

    })

  },

  //扫描记录导出文件
  requestExportScanList: function (context, lineName, programName, equipmentName, standPosition, startTime, endTime, exportData) {

    if (startTime !== '') {
      startTime = new Date(startTime).getTime()

    }
    if (endTime !== '') {
      endTime = new Date(endTime).getTime()
    }

    var data = {
      params: {
        //筛选信息
        lineName: lineName,
        programName: programName,
        equipmentName: equipmentName,
        username: "",
        standPosition: standPosition,
        startTime: startTime,
        endTime: endTime,


        //导出信息
        orderNo: exportData.orderNum,
        orderQuantity: exportData.orderCount,
        customerName: exportData.customName,
        productName: exportData.productName,
      }
    };
    myGet(Api.exportScanListUrl, data, function (response) {

      var data = response.data.data
      mainVue.$message({showClose: true, message: '导出成功，正在生成文件', type: 'success'});
      MyUtil.downLoadFile('.' + data.path)
    })

  },

  requestDeleteScanList: function (context, ids) {

    context.isDeleteBtnLoading = true
    var data = {
      params: {
        ids: ids.join(),//1,2,1,3
      }
    };

    function everyTodo() {
      context.isDeleteBtnLoading = false
    }

    myGetWithoutLoad(Api.deleteScanListUrl, data, function (response) {

      ids.forEach(function (item) {
        context.tableData.forEach(function (inItem, inIndex) {
          if (inItem.id === item) {
            context.tableData.splice(inIndex, 1)
          }
        })
      })
      mainVue.$message({showClose: true, message: '删除成功', type: 'success'});
    }, everyTodo)

  },


  requestCancelHighLightScanList: function (context, ids) {

    context.isCancelLightBtnLoading = true
    var data = {
      params: {
        ids: ids.join(),//1,2,1,3
      }
    };

    function everyTodo() {
      context.isCancelLightBtnLoading = false
    }

    myGetWithoutLoad(Api.cancelHighLightScanListUrl, data, function (response) {

      ids.forEach(function (item) {

        var datas = MyUtil.copyArr(context.tableData)

        datas.forEach(function (inItem, inIndex) {
          if (inItem.id === item) {
            inItem.isShowHighLight = false
          }
        })
        context.tableData = datas
      })


      mainVue.$message({showClose: true, message: '高亮取消成功', type: 'success'});
    }, everyTodo)

  },


  requestBomList: function (context, lineName) {
    var data = {
      params: {
        lineName: lineName,
      }
    }
    myGet(Api.bomListUrl, data, function (response) {

      var data = response.data.data
      // console.log(response)
      var header = [{type: "index", isShow: true}, {prop: 'bomname', label: '名称', isShow: true}]
      var tableData = []
      data.forEach(function (item) {
        // console.log(item)
        var c = {bomname: item}
        tableData.push(c)
      })
      context.tableHeader = header
      context.tableData = tableData
      context.page = MyUtil.tableData.makePage(data.pageNum, data.pageSize, data.total)
    })
  },


  requestClientList: function (context, pageNum, pageSize) {
    var data = {

      params: {
        page: pageNum,
        size: pageSize,
      }


    }
    myGet(Api.clientListUrl, data, function (response) {

      var data = response.data.data

      context.tableHeader = MyUtil.tableData.makeClientHeader()
      context.tableData = MyUtil.tableData.makeClientList(data.list)
      context.page = MyUtil.tableData.makePage(data.pageNum, data.pageSize, data.total)

    })
  },


  requestSpeclibList: function (context, clientid, pageNum, pageSize) {
    var data = {
      params: {
        clientid: clientid,
        page: pageNum,
        size: pageSize,
      }
    }

    myGet(Api.speclibListUrl, data, function (response) {
      var data = response.data.data
      // console.log(response)


      var tableData = MyUtil.tableData.makeSpeclibList(data.list)
      var tableHeader = MyUtil.tableData.makeSpeclibHeader(data.header)
      tableHeader = MyUtil.tableData.setTableHeaderAutoWidth(tableHeader, tableData)
      context.tableHeader = tableHeader
      context.tableData = tableData

      // context.tableHeader = MyUtil.tableData.makeSpeclibHeader(data.header)
      // context.tableData = MyUtil.tableData.makeSpeclibList(data.list)
      context.page = MyUtil.tableData.makePage(data.pageNum, data.pageSize, data.total)
    })
  },

  autoMenuRequest: function (context) {


    //自动请求menu菜单
    var data = {};
    myGetWithoutLoad(Api.menuListUrl, data, function (response) {
      var menuLists = addMenuListRoute(response.data.data)
      context.menuList = menuLists
    }, function () {

    })
  }

}


function loginSuccess(response, isRemember) {
  mainVue.$message({showClose: true, message: '登录成功', type: 'success'});
  MyUtil.saveTokenId(response.data.data.tokenId, isRemember)
  //跳转
  setTimeout(function () {
    window.location.href = Api.indexPage
  }, 800)
}


/*对菜单进行跳转链接的设置*/
function addMenuListRoute(menuList) {

  for (var i = 0; i < menuList.length; i++) {

    var menu = menuList[i]
    if (menu.index === "scan") {
      for (var j = 0; j < menu.children.length; j++) {
        menu.children[j].index = '/programlist?chanxian=' + menu.children[j].index
      }
    }
    else if (menu.index === "program") {
      for (var j = 0; j < menu.children.length; j++) {
        menu.children[j].index = '/programfilelist?chanxian=' + menu.children[j].index
      }
    }

    else if (menu.index === "spec") {
      // menu.index = "speclib"

      menu.index = "clientlist"

    }

    else if (menu.index === "bom") {
      for (var j = 0; j < menu.children.length; j++) {
        menu.children[j].index = '/bomlist?chanxian=' + menu.children[j].index
      }
    }
    else if (menu.index === 'usermanage') {
      menuList.splice(i, 1)//权哥 要求 暂时 隐藏
    }
  }
  return menuList
}


/*处理表头*/


function showTableColumn(header) {

  for (var i in header) {
    header[i].isShow = true
    header[i].width = 180
  }

  return header
}


















